// components/city_selector/city_selector.js
const app = getApp();
const region = require("city_0.js");
const QQMapWX = require('qqmap-wx-jssdk.js');
let qqmapsdk, map_key = 'NYUBZ-DIM66-5SHSW-MMZFG-57AX3-SJFOB';

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    show_sel:!1,
    area_list: [],
    selCitys: [[], []],
    province_index: 0,
    area_index: 0,
    sel_all: !1,
    sel_data: {},
    sub_data:{},
    sel_img:'sel_0.png'
  },
  created(){
    qqmapsdk = new QQMapWX({
      key: map_key
    });
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //区域弹框
    selCity: function () {
      if (this.data.area_list.filter(v => !!v.select).length < 1) {
        this.authHandle("location", () => {
          this.getLocal();
        }, () => {
          this.cityFormat("浙江省", "杭州市");
          let sub = wx.getStorageSync("spon_data");
          this.setData({
            temp_depict: sub.depict || "",
            sel_all: !1,
            show_sel: !0
          })
        }, () => {
          let sub = wx.getStorageSync("spon_data");
          this.setData({
            temp_depict: sub.depict || "",
            show_cover: !0
          })
        });
      } else {
        this.setData({
          show_sel: !0,
        });
      }
    },
    // 隐藏选框
    hideSel: function () {
      this.selDataHandle();
      this.computePrice();
      this.setData({
        show_sel: 0
      });
    },
    //选择合计
    selDataHandle: function () {
      let li = this.data.area_list, arr = li.filter(v => !!v.select), d = this.data.sel_data;
      if (this.data.province) {
        d[this.data.province] = arr
        this.setData({
          sel_data: d
        });
      }
      // console.log(d);
      return d;
    },
    //获取地址
    getLocal: function () {
      wx.showLoading({
        title: '定位中'
      });
      let addr = qqmapsdk.reverseGeocoder({
        success: res => {
          // console.log(res)
          if (res && res.status === 0 && (res.result && res.result.address)) {
            let d = this.data.sub_data, r = res.result.address_component;
            d.province = r.province + "," + r.city;
            // console.log(d, region, region.region[r.province][r.city]);
            if (region.region[r.province] && region.region[r.province][r.city]) {
              this.cityFormat(r.province, r.city);
              let sub = wx.getStorageSync("spon_data");
              // console.log(sub)
              this.setData({
                sel_all: !1,
                show_sel: !0
              });
            }
          }
        },
        fail: err => {
          console.log(err)
          if (err && err.status === 1000) {
            app.authHandle("location", () => {
              this.getLocal();
            }, 0, () => {
              this.setData({
                show_cover: !0
              })
            });
          }
        },
        complete: function () {
          wx.hideLoading();
        }
      })
    },
    //省市变更
    cityChange: function (e) {
      // console.log(e);
      this.selDataHandle();//获取选择区域
      let arr = this.data.selCitys;
      let p = arr[0][this.data.province_index], c = arr[1][0];
      if (e.detail.column === 0) {
        // console.log(p);
        p = arr[0][e.detail.value];
        this.cityFormat(p, 0, c => {
          c = c;
          this.setData({
            province: p + "," + c
          });
        });
      }
      if (e.detail.column === 1) {
        c = arr[1][e.detail.value];
        this.setData({
          province: p + "," + c
        });
        this.changeErea(p, c);
      }
    },
    //城市更换
    cityFormat: function (province, city, fn) {
      let obj = region.region;
      let arr = [[], []];
      for (let k in obj) {
        arr[0].push(k)
      }
      // console.log(arr);
      if (province) {
        let i = arr[0].indexOf(province), j;
        if (i > -1) {
          for (let k in obj[province]) {
            arr[1].push(k);
          }
          j = arr[1].indexOf(city)
          this.setData({
            province_index: i,
            area_index: j > 0 ? j : 0
          });
        }
      } else {
        arr[1] = obj[arr[0][0]][arr[0][0]];
      }
      // console.log(arr);
      this.setData({
        selCitys: arr
      });
      city = city ? city : arr[1][0];
      this.changeErea(province, city);
      if (typeof fn == "function") { fn(arr[1][0]); }
    },
    //地区设置
    changeErea: function (p, c) {
      let pic = this.data.selCitys, obj = region.region, li = [];
      p = p ? p : pic[0][0];
      c = c ? c : pic[1][0];
      // console.log(obj[p][c]);
      obj[p][c].forEach(v => {
        li.push({
          area: v,
          select: !1
        })
      })
      //重赋选区
      let d = this.data.sel_data, count = 0, all = !1;
      // console.log(p, c, p + "," + c in d);
      if ((p + "," + c) in d) {
        li.forEach(v => {
          d[p + "," + c].forEach(v1 => {
            if (v1.area == v.area) {
              v.select = !0;
              count++;
            }
          });
        });
        if (li.length == count) {
          all = !0
        }
      }
      // console.log(d[p + "," + c], li, all)
      this.setData({
        area_list: li,
        sel_all: all,
        province: p + "," + c
      });
      this.computePrice();
    },
    // 全选
    selAll: function () {
      let li = this.data.area_list, sel_all = this.data.sel_all;
      sel_all = !sel_all;
      li.forEach(v => {
        v.select = sel_all;
      })
      this.setData({
        area_list: li,
        sel_all: sel_all
      })
    },
    //删除
    delectSel: function (e) {
      let i = e.currentTarget.dataset.index, k = e.currentTarget.dataset.k, d = this.data.sel_data, s = this.data.area_list;
      // 选框重赋
      if (k == this.data.province) {
        // console.log(i, k, d[k], d[k][i]);
        for (let j = 0; j < s.length; j++) {
          if (s[j].area == d[k][i].area) {
            s[j].select = !1;
            this.setData({
              sel_all: !1,
              area_list: s
            });
            break;
          }
        }
      }
      d[k].splice(i, 1);
      if (d[k].length == 0) { delete d[k] }
      this.setData({
        sel_data: d
      });
      this.computePrice();
    },
    //选择
    selectThis: function (e) {
      let i = e.currentTarget.dataset.index, li = this.data.area_list, param = {}, sel_all = this.data.sel_all;
      li[i].select = !li[i].select;
      param[`area_list[${i}].select`] = li[i].select;
      // console.log(sel_all, !li.find(v => !v.select))
      param.sel_all = sel_all ? !1 : !li.find(v => !v.select);
      // console.log(param);
      this.setData(param)
    },
    rf:()=>{},
    //计算费用
    computePrice: function () {
      let d = this.data.sel_data, arr = [], ar = [], pro = [];
      // console.log(d);
      for (let k in d) {
        if (Array.isArray(d[k]) && d[k].length > 0) {
          pro.push(k);
          ar.push([]);
          d[k].forEach(v => {
            if (v.area) {
              arr.push(v.area);
              ar[ar.length - 1].push(v.area);
            }
          })
        }
      }
      // console.log(pro,arr);
      //规则
      this.setData({
        "sub_data.showAddress": ar.join(";"),
        "sub_data.province": pro.join(";"),
        "sub_data.length": arr.length
      });
      this.triggerEvent("mychange", this.data.sub_data)
    },
    //授权处理
    authHandle(str, scb, fcb, ucanel, lcancel) {
      switch (str) {
        case "location":
          wx.getSetting({
            success: res => {
              // console.log(res, res.authSetting["scope.userLocation"]);
              if (res.authSetting["scope.userLocation"]) {
                if (typeof scb == "function") { scb(); }
              } else if (res.authSetting["scope.userLocation"] === void 0) {
                this.getMyPosition();
              } else {
                wx.showModal({
                  title: '提示',
                  content: '您未授权位置信息，是否去设置？',
                  success: res => {
                    if (res.confirm) {
                      wx.openSetting({
                        success: res => {
                          // console.log(res);
                          if (!res.authSetting["scope.userInfo"]) {
                            wx.removeStorageSync("login_info");
                            wx.showToast({
                              title: '授权被取消',
                            });
                            if (typeof ucanel == "function") { ucanel(); }
                          } else if (res.authSetting["scope.userLocation"]) {
                            if (typeof scb == "function") { scb(); }
                          }
                        }
                      });
                    } else {
                      if (typeof lcancel == "function") { lcancel(); }
                    }
                  },
                  fail: err => {
                    if (typeof fcb == "function") { fcb(); }
                  }
                })
              }
            }
          });
          break;
        case "userInfo": break;
        default:break;
      }
    },
    //获取当前位置
    getMyPosition: function () {
      wx.getLocation({
        success: function (res) {
          let param = {};
          param.locations = res.latitude + "," + res.longitude;
          param.type = 5;
          param.key = map_key;
          return param.locations;
        },
        fail: res => { }
      })
    },
  }
})
